<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线聊天Demo</title>
    <script src="/static/js/jquery-3.6.0.js"></script>
    <style>
        .messageLeft {
            margin: 20px 0;
            text-align: left;
        }

        .messageLeft > div:nth-of-type(1) {
            font-size: 16px;
            font-weight: bolder;
        }

        .messageLeft > div:nth-of-type(2) {
            padding-left: 20px
        }

        .messageRight {
            margin: 20px 0;
            text-align: right;
        }

        .messageRight > div:nth-of-type(1) {
            font-size: 16px;
            font-weight: bolder;
        }

        .messageRight > div:nth-of-type(2) {
            padding-right: 20px
        }
    </style>
    <script>
        $(function () {
            var username; //当前用户名
            var toUsername ="大厅";//默认是在大厅聊天
            //简单模拟的用户登陆
            while (!username) {
                username = prompt("请输入名称");
            }
            var ws = new WebSocket("ws://localhost:8080/chat/" + username);
            var resultObj;//接受到的推送数据
            ws.onopen = function () {
                console.log("websocket连接成功")
            }

            ws.onmessage = function (event) {
                resultObj = JSON.parse(event.data);
                console.log('收到推送数据-------》》', resultObj)
                $("#onlineCount").text("当前在线人数：" + resultObj.onlineCount + "人");
                //展示好友在线列表
                if (resultObj.onlineUsernames) {
                    $("#userList").empty();
                    $("#userList").append(`<p><a href="">大厅</a></p>`)
                    for (let name of resultObj.onlineUsernames) {
                        if (name != username) {
                            $("#userList").append(`<p><a href="">${name}</a></p>`)
                        }
                    }
                }
                //展示接受到的消息
                if (resultObj.message) {
                    var html = `<div class="${resultObj.fromUsername == username ? 'messageRight' : 'messageLeft'}">
                                    <div>${resultObj.fromUsername}</div>
                                    <div>${resultObj.message}</div>
                                </div>`;
                    $("#chat").append(html);
                    //将接受到的消息存储到sessionStorage对象中，便于加载数据
                    if(resultObj.toUsername=='大厅'){
                        var chatData = sessionStorage.getItem('大厅');
                        if(chatData){
                            html = chatData +html;
                        }
                        sessionStorage.setItem('大厅',html);
                    }else{
                        var chatData = sessionStorage.getItem(resultObj.fromUsername);
                        if(chatData){
                            html = chatData +html;
                        }
                        sessionStorage.setItem(resultObj.fromUsername,html);
                    }

                }
            }

            ws.onclose = function () {
                console.log("websocket连接关闭")
            }

            $("#sendBtn").click(function () {
                var msg = $("#message").val();
                var json = {'fromUsername': username, 'toUsername': toUsername, 'message': msg};
                ws.send(JSON.stringify(json));//向服务端推送数据
                $("#message").val('');//清除输入框的内容
                //如果指定了发送给谁的消息，则同步储存到sessionStorage中
                if(toUsername && toUsername!='大厅'){
                    var html = `<div class="messageRight">
                                    <div>${username}</div>
                                    <div>${msg}</div>
                                </div>`;
                    $("#chat").append(html)
                    var chatData = sessionStorage.getItem(toUsername);
                    if(chatData){
                        html = chatData +html;
                    }
                    sessionStorage.setItem(toUsername,html);
                }

            });

            //点击好友列表，先清除当前聊天内容，并加载对应的聊天记录
            $("#userList").on("click","a",function () {
                toUsername = $(this).text();
                $("#title").text("正在和"+toUsername+"聊天");
                let chatData = sessionStorage.getItem(toUsername);
                $("#chat").empty().html(chatData);
                return false;
            })
        })
    </script>
</head>
<body>
<h2 id="onlineCount"></h2>
<p id="title">正在大厅聊天</p>
<div style="display: flex;">
    <div id="chatBox" style="flex: 3;border: black 1px solid">
        <div id="chat" style="height: 300px;padding: 15px;overflow: auto;">
        </div>
        <div id="inputDiv">
            <textarea name="" id="message" style="width: 99.5%;height: 150px;"></textarea>
            <button id="sendBtn">发送</button>
        </div>
    </div>
    <div id="userList" style="flex: 1;border: black 1px solid"></div>
</div>
</body>
</html>